import { CanActivate, ExecutionContext, Injectable, UnauthorizedException } from '@nestjs/common'
import { AuthService } from '../modules/auth/auth.service'

@Injectable()
export class AuthGuard implements CanActivate {
    constructor(
        private readonly authService: AuthService
    ) { }

    canActivate(content: ExecutionContext) {
        const request = content.switchToHttp().getRequest()
        let token = request.headers['authorization']

        if (!token) return false
        if (!token.startsWith('Bearer ')) return false
        token = token.replace('Bearer ', '')

        try {
            const user = this.authService.validateToken(token)
            if (user === false) {
                return false
            } else {
                request['userId'] = user.userId
            }
        }
        catch (err) {
            throw new UnauthorizedException();
        }
        return true
    }

}